/**
 * @author 艾尼亚尔
 * @date 2025/8/7
 * @description 路由守卫
 */
import type {Router, RouteLocationNormalized, NavigationGuardNext, RouteRecordRaw} from 'vue-router'
import type {LoadingBarApi} from 'naive-ui'
import {getToken} from '@/utils/storage.ts'
import {appStoreWidthOut} from '@/stores/app.ts'
import {config} from '@/config'

export function createRouterGuards(router: Router) {
    // 前置守卫
    router.beforeEach(async (to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
        const token = getToken()
        const appStore = appStoreWidthOut()

        // 类型安全的加载条访问
        const Loading = (window as { $loading?: LoadingBarApi }).$loading

        // 开始加载进度条
        Loading?.start()

        // 未登录情况处理
        if (!token) {
            if (to.name !== 'login') {
                next({name: 'login'})
            } else {
                next()
            }
            return
        }

        // 已登录但访问登录页，重定向到首页
        if (to.name === 'login' && token) {
            next({path: '/home'})
            return
        }

        if (appStore.isDynamicAddedRoute) {
            next();
            return;
        }
        //赋值菜单数据
        const routes = await appStore.generateRoutes();
        // 动态添加可访问路由表
        routes.forEach((item) => router.addRoute(item as unknown as RouteRecordRaw));

        const redirectPath = (from.query.redirect || to.path) as string;
        const redirect = decodeURIComponent(redirectPath);
        const nextData = to.path === redirect ? {...to, replace: true} : {path: redirect};
        appStore.setDynamicAddedRoute(true);
        next(nextData);
        return;
    })

    // 后置守卫
    router.afterEach((to: RouteLocationNormalized) => {
        const Loading = (window as { $loading?: LoadingBarApi }).$loading

        // 设置页面标题
        let title = ''
        if (to.meta && typeof to.meta.title === 'string') {
            title = to.meta.title
        }

        document.title = `${config.Title}-${title.replace(/\s/g, '')}`

        // 结束加载进度条
        Loading?.finish()
    })

    // 路由错误处理
    router.onError((error: Error) => {
        const Loading = (window as { $loading?: LoadingBarApi }).$loading
        Loading?.error()
        console.error('路由错误:', error)
    })
}
